import React, { useEffect, useImperativeHandle, useState } from 'react';
import { Button, message, Select } from 'antd';
import { connect } from 'dva';
import { flattenToCodeNameMap, getQuery, getPath } from '@/utils/marketingMap/utils';

import styles from './index.less';

interface Props {
  permissions: string[];
  type: number;
  value: any;
  options: any;
  trr: any;
  defaultValue: any;
  onSubmit: any;
  dispatch: any;
}

const SearchTable: React.FC<Props> = ({ type, dispatch, options, onSubmit, trr }) => {
  const [initialValue, setInitialValue] = useState<any>({});
  const [query, setQuery] = useState({
    region: '',
    subregion: '',
    city: '',
    store: '',
    areaRange: 10,
    brand: 'DFPV',
  });

  const updateQuery = {
    region: (value: string) => {
      const subregion = getQuery(options, value);
      const city = getQuery(options, value, subregion);
      const store = getQuery(options, value, subregion, city);
      setQuery({ ...query, region: value, subregion, city, store });
    },
    subregion: (value: string) => {
      const city = getQuery(options, query.region, value);
      const store = getQuery(options, query.region, value, city);

      setQuery({ ...query, subregion: value, city, store });
    },
    city: (value: string) => {
      const store = getQuery(options, query.region, query.subregion, value);

      setQuery({ ...query, city: value, store });
    },
    default: (key: string, value: string | number) => {
      setQuery({ ...query, [key]: value });
    },
  };

  useEffect(() => {
    if (!trr.length) {
      dispatch({
        type: 'afterSalesAnalysis/getTree',
        payload: { url: '/org/tree' },
      });
    }
  }, []);

  useEffect(() => {
    if (!Object.keys(options).length) {
      dispatch({
        type: 'afterSalesAnalysis/getOptions',
        payload: { type },
      });
    }
  }, [type]);

  useEffect(() => {
    if (options && trr) {
      if (window.sessionStorage.getItem('marketingMapQuery')) {
        const marketingMapQuery = JSON.parse(
          window.sessionStorage.getItem('marketingMapQuery') || '{}',
        );
        setQuery(marketingMapQuery);
        return;
      }

      if (trr) {
        const paths = getPath(options, trr.orgCode);

        if (paths) {
          const [region, subregion, city, store] = paths;
          setInitialValue({
            region,
            subregion,
            city,
            store,
            areaRange: 10,
            brand: 'DFPV',
            // timeRange: '1',
            // summaryDate: moment().add(-2, 'd').format('YYYY-MM-DD'),
          });
        } else {
          // if (auth) {
            setInitialValue({
            region: 'HZ',
            subregion: 'WH',
            city: '1801',
            store: 'HUB46',
            areaRange: 10,
            brand: 'DFPV',
            // timeRange: '1',
            // summaryDate: moment().add(-2, 'd').format('YYYY-MM-DD'),
          });
          // } else {
          //   message.error('无数据权限，请联系管理员');
          // }
        }
      }
    }
  }, [trr, options]);

  return (
    <div className={styles.wrapper}>
      <div className={styles.card}>
        <Select
          bordered={false}
          placeholder="大区"
          className={styles.input}
          size="small"
          value={query.region}
          onChange={value => updateQuery['region'](value)}
          style={{ width: 94 }}
        >
          {Object.keys(options).map(key => (
            <Select.Option value={key} key={key}>
              {options[key].name}
            </Select.Option>
          ))}
        </Select>
        <Select
          bordered={false}
          placeholder="小区"
          className={styles.input}
          size="small"
          style={{ width: 94 }}
          value={query.subregion}
          onChange={value => updateQuery['subregion'](value)}
        >
          {Object.keys(options[query.region]?.children || {}).map(key => (
            <Select.Option value={key} key={key}>
              {(options[query.region]?.children || {})?.[key]?.name}
            </Select.Option>
          ))}
        </Select>
        <Select
          bordered={false}
          placeholder="城市"
          className={styles.input}
          size="small"
          style={{ width: 94 }}
          value={query.city}
          onChange={value => updateQuery['city'](value)}
        >
          {Object.keys(options[query.region]?.children?.[query.subregion]?.children || {}).map(
            key => (
              <Select.Option value={key} key={key}>
                {(options[query.region]?.children?.[query.subregion]?.children || {})?.[key]?.name}
              </Select.Option>
            ),
          )}
        </Select>
        <Select
          bordered={false}
          placeholder="专营店"
          className={styles.input}
          size="small"
          style={{ minWidth: 120, maxWidth: 234 }}
          value={query.store}
          onChange={value => updateQuery['default']('store', value)}
        >
          {Object.keys(
            options[query.region]?.children?.[query.subregion]?.children?.[query.city]?.children ||
              {},
          ).map(key => (
            <Select.Option value={key} key={key}>
              {
                (options[query.region]?.children?.[query.subregion]?.children?.[query.city]
                  ?.children || {})?.[key]?.name
              }
            </Select.Option>
          ))}
        </Select>
        <Select
          bordered={false}
          placeholder="区域范围"
          className={styles.input}
          style={{ width: 132 }}
          size="small"
          allowClear
          value={query.areaRange}
          onChange={value => updateQuery['default']('areaRange', value)}
        >
          {/* <Select.Option value={5}>区域范围 5km</Select.Option> */}
          <Select.Option value={10}>区域范围 10km</Select.Option>
          <Select.Option value={20}>区域范围 20km</Select.Option>
        </Select>
        <Select
          bordered={false}
          placeholder="品牌"
          size="small"
          // className={styles.input}
          style={{ width: 94 }}
          value={query.brand}
        >
          <Select.Option value="DFPV">风神</Select.Option>
        </Select>
        {/* <Select bordered={false} placeholder="车系" size="small" style={{ minWidth: 98 }}>
          <Select.Option value={1}>1</Select.Option>
        </Select> */}
        <Button type="primary" htmlType="submit" className={styles.btn}>
          查询
        </Button>
      </div>
      <Button className={styles.reset}>重置</Button>
    </div>
  );
};

export default connect(({ menu, afterSalesAnalysis }: any) => ({
  permissions: menu.permissions,
  options: afterSalesAnalysis.options,
  trr: afterSalesAnalysis.trr,
}))(SearchTable);
